import { ThenableWebDriver, Builder } from "selenium-webdriver"
import firefox from "selenium-webdriver/firefox"

export abstract class AutoDeployBlog {

    protected driver: ThenableWebDriver
    protected cookies: string
    protected blogContent: blogContent

    protected homeUrl: string
    protected mdUrl: string
    protected domain: string
    protected httpOnlyCookies: Array<string>
    protected secureCookies: Array<string>
    protected xpath: xpathConfig

    protected constructor(cookies: string, blogContent: blogContent) {
        this.cookies = cookies
        this.blogContent = blogContent
        this.driver = new Builder()
            .forBrowser('firefox')
            .setFirefoxService(new firefox.ServiceBuilder("./geckodriver.exe"))
            // .setFirefoxOptions(new firefox.Options().headless())
            .build();
    }

    abstract deploy(): Promise<string>

    protected async cookiesLogin() {
        await this.driver.manage().deleteAllCookies()
        let array = cookies.split(';').map(_ => _.trim());

        for (let i = 0; i < array.length; i++) {
            const item = array[i];
            let index = item.indexOf('=')
            let key = item.substring(0, index) // cookies 每一项的键
            let value = item.substring(index + 1) // cookies 每一项的值
            if (value) {
                await driver.manage().addCookie({
                    name: key,
                    value: value,
                    domain: this.domain,
                    httpOnly: !!this.httpOnlyCookies.find(_ => _ == key),
                    secure: !!this.secureCookies.find(_ => _ == key),
                });
            }
        }
        // 查看所有 Cookies
        this.driver.manage().getCookies().then(function (cookies) {
            console.log('cookie details => ', cookies);
        });
    }
}